<?php
/**
 * Created by PhpStorm.
 * User: Dick
 * Date: 2016/4/12
 * Time: 16:46
 */

namespace Model;


class Follow
{
    public $following;
    public $followed;

    public static function addfollow($following, $followed)
    {
        global $pdo;
        $inTransaction = $pdo->inTransaction();
        if (!$inTransaction) {
            $pdo->beginTransaction();
        }
        $statament = $pdo->prepare('SELECT COUNT(*) FROM user WHERE id=?');
        $statament->bindValue(1, $followed);
        $statament->execute();
        $flag = $statament->fetchColumn();
        if ($flag == 0) {
            $followed = User::GetIdByUsername($followed);
        }
        $statament = $pdo->prepare('INSERT INTO follow SET following=:following,followed=:followed');
        $statament->bindValue(':following', $following);
        $statament->bindValue(':followed', $followed);
        $statament->execute();
        if (!$inTransaction) {
            $pdo->commit();
        }
    }

    public static function delfollow($following, $followed)
    {
        global $pdo;
        $inTransaction = $pdo->inTransaction();
        if (!$inTransaction) {
            $pdo->beginTransaction();
        }
        $followed = User::GetIdByUsername($followed);
        $statament = $pdo->prepare('DELETE FROM follow WHERE following=:following && followed=:followed');
        $statament->bindValue(':following', $following);
        $statament->bindValue(':followed', $followed);
        $statament->execute();
        if (!$inTransaction) {
            $pdo->commit();
        }
    }


    public static function GetFollow($following, $followed)
    {
        global $pdo;
        $statament = $pdo->prepare('SELECT * FROM follow WHERE following=?');
        $statament->bindValue(1, $following);
        $statament->execute();
        $result = $statament->fetchAll();
        $followed = User::GetIdByUsername($followed);
        foreach ($result as $key => $value) {
            if ($result[$key]['followed'] == $followed) {
                echo 1;
                return;
            } else {
                echo 0;
            }
        }
    }

    public static function GetFollowing($following, $followed)
    {
        global $pdo;
        $followed = User::GetIdByUsername($followed);
        $statament = $pdo->prepare('SELECT COUNT(*) FROM follow WHERE following=? && followed=?');
        $statament->bindValue(1, $following);
        $statament->bindValue(2, $followed);
        $statament->execute();
        $result = $statament->fetchColumn();
        return $result;
    }

}